package org.nowcoder.leetcode.DP;

/**
 * Title  : 1143. Longest Common Subsequence
 * Source : https://leetcode.cn/problems/longest-common-subsequence/description/
 * Author : XrazYang
 * Date   : 2023-12-20
 */

public class LeetCode_1143 {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        //1. 定义状态：dp[i][j],表示text1[0:i] 和text2[0:j]的最长公共子序列长度
        //2. 初始状态：默认从初始化
        int[][] dp = new int[m + 1][n + 1];

        //3.状态转移方程
        for (int i = 1; i <= m; i++) {
            char c1 = text1.charAt(i - 1);
            for (int j = 1; j <= n; j++) {
                char c2 = text2.charAt(j - 1);
                if (c1 == c2) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[m][n];
    }
}
